'''

    用来处理流程用例、单接口、ddt数据驱动用例

'''
import yaml

from common.requests_until import logger


def read_testcase(yaml_path):
    with open(yaml_path, encoding='gbk') as f:
        case_list = yaml.safe_load(f)
        if len(case_list) >=2 : # 流程用例
            # print("流程用例: %s" %case_list)  # 原来是[{},{}]
            return [case_list]  # 返回[[{},{}]]
        else:
            if "parametrize" in dict(*case_list).keys():
                new_case_list = ddts(*case_list, yaml_path.name)
                return new_case_list
            else:
                # print("单接口用例:%s"%case_list)
                return case_list

def ddts(case_list: dict,yaml_path_name):
    # print("数据驱动用例,返回[{},{},{}]")
    params = case_list["parametrize"]

    len_flag = True
    params_len = len(params[0])

    for param in params:
        if len(param) != params_len:
            len_flag = False
            logger.error(yaml_path_name+":数据驱动用例参数长度不一致\n")
            break

    caseinfo_str = yaml.safe_dump(case_list)
    new_caseinfo = []
    # 如果没问题的话
    if len_flag:
        for x in range(1,len(params)):
            raw_caseinfo = caseinfo_str
            # print("--行: %s"%x)
            for y in range(params_len):
                # print("---列: %s"%y,params[0][y],params[x][y])
                if isinstance(params[x][y],str) and params[x][y].isdigit():
                    params[x][y] = "'"+params[x][y]+"'"
                raw_caseinfo = raw_caseinfo.replace("$ddt{"+params[0][y]+"}",params[x][y])
            case_dict = yaml.safe_load(raw_caseinfo)
            # print("---用例: %s"%case_dict)
            case_dict.pop("parametrize")
            new_caseinfo.append(case_dict)

    return new_caseinfo




